<template>
  <div class="app-container p-n">
    <el-row type="flex" class="row-bg" justify="space-around">
      <el-col :span="23">
        <div class="grid-content bg-white min-h-800">
          <!--搜索区域-->
          <el-row :gutter="10" class="p-15">
            <!--技能组筛选条件-->
            <el-col :xs="24" :sm="10" :md="4" :lg="4" :xl="3" class="p-t-5">
              <el-select
                v-model="searchQuery.groupTypeId"
                placeholder="请选择技能组"
                style="width: 250px;"
              >
                <el-option label="全部" value/>
                <el-option label="工单客服" value="1"/>
                <el-option label="服务星客服" value="2"/>
                <el-option label="供给人员" value="3"/>
              </el-select>
            </el-col>

            <el-col :xs="24" :sm="10" :md="8" :lg="5" :xl="3">
              <el-row :gutter="10">
                <el-col :span="16" class="p-t-5">
                  <el-input v-model="searchQuery.keyword" placeholder="客服昵称/微信号" clearable/>
                </el-col>
                <el-col :span="8" class="p-t-5">
                  <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-search"
                    @click="getTableData('ture')"
                  >{{ $t('table.search') }}</el-button>
                </el-col>
              </el-row>
            </el-col>

            <el-col :xs="12" :sm="6" :md="4" :lg="3" :xl="2" class="p-t-5">
              <el-button
                class="filter-item"
                type="success"
                icon="el-icon-edit"
                @click="showSeatTable(null,'添加')"
              >添加坐席</el-button>
            </el-col>

            <!-- <el-col :xs="12" :sm="6" :md="4" :lg="3" :xl="2" class="p-t-5">
              <el-button
                class="filter-item"
                type="warning"
                icon="el-icon-edit"
                @click="porpAdd1(null,'添加')"
              >+配置项</el-button>
            </el-col>-->
          </el-row>

          <!--表格区域-->
          <el-row :gutter="10">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <div class="grid-content p-15">
                <el-table :data="tableData" border stripe style="width: 100%">
                  <el-table-column prop="name" label="操作" width="250">
                    <template slot-scope="scope">
                      <el-button
                        :disabled="scope.row.skillsGroupId === 2"
                        type="danger"
                        size="mini"
                        class="cancel-btn"
                        icon="el-icon-delete"
                        @click="deleteCusSeat(scope.row)"
                      >删除</el-button>
                      <el-button
                        type="warning"
                        size="mini"
                        icon="el-icon-edit"
                        @click="showSeatTable(scope.row,'修改')"
                      >修改坐席</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column prop="date" label="头像" width="180">
                    <template slot-scope="scope">
                      <img :src="scope.row.kfWeixiuImg" style="height: 50px;">
                    </template>
                  </el-table-column>
                  <el-table-column prop="kfUserName" label="用户名称">
                    <template slot-scope="scope">
                      <a
                        v-if="scope.row.skillsGroupId === 3"
                        style="text-decoration:underline;color: blue;"
                        @click="showPioneerUrl(scope.row.seatTableId)"
                      >{{ scope.row.kfUserName }}</a>
                      <span v-if="scope.row.skillsGroupId !== 3">{{ scope.row.kfUserName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="kfNickname" label="客服昵称"/>
                  <el-table-column prop="kfWeixinNumber" label="微信号"/>
                  <el-table-column prop="kfContact" label="联系方式"/>
                  <el-table-column prop="skillsGroupName" label="技能组"/>
                  <el-table-column prop="serviceObjectNames" label="服务对象">
                    <template slot-scope="scope">
                      <a
                        v-if="scope.row.skillsGroupId === 1 && scope.row.serviceObjectNames!=='' && scope.row.serviceObjectNames!==null"
                        href="#"
                        style="text-decoration:underline;color: blue;"
                        @click="porpAdd1(scope.row,'修改')"
                      >{{ scope.row.serviceObjectNames }}</a>
                      <el-button
                        v-if="scope.row.skillsGroupId === 1 && (scope.row.serviceObjectNames=='' || scope.row.serviceObjectNames===null)"
                        class="filter-item"
                        type="warning"
                        icon="el-icon-edit"
                        @click="porpAdd1(scope.row,'添加')"
                      >+配置项</el-button>

                      <span v-if="scope.row.skillsGroupId == 2">--</span>
                    </template>
                  </el-table-column>
                </el-table>
                <!--分页-->
                <div class="pagination-container">
                  <el-pagination
                    :current-page="searchQuery.page"
                    :page-sizes="[5,10,20,30, 50]"
                    :page-size="searchQuery.pageSize"
                    :total="total"
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                  />
                </div>
              </div>
            </el-col>
          </el-row>

          <!--弹出坐席维护框start-->
          <el-dialog
            :title="dialogStatus"
            :visible.sync="seatTableDialogVisible"
            :before-close="hideSeatTableForm"
            width="550px"
          >
            <el-form
              ref="seatTableForm"
              :model="seatForm"
              :rules="seatFormRules"
              label-width="100px"
            >
              <el-form-item label="用户" prop="kfUserId">
                <el-select
                  v-model="seatForm.kfUserId"
                  filterable
                  placeholder="请选系统用户(可搜索)"
                  style="width: 250px;"
                >
                  <el-option
                    v-for="(user,index) in userList"
                    :label="user.name"
                    :value="user.id"
                    :key="index"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="技能组" prop="skillsGroupId">
                <el-select
                  v-model="seatForm.skillsGroupId"
                  :disabled="disabledSkillsGroup"
                  placeholder="请选择技能组"
                  style="width: 250px;"
                  @change="serivceStarCusAddValidate"
                >
                  <el-option label="工单客服" value="1"/>
                  <el-option label="服务星客服" value="2"/>
                  <el-option label="供给人员" value="3"/>
                </el-select>
              </el-form-item>
              <el-form-item label="昵称" prop="kfNickname">
                <el-input v-model="seatForm.kfNickname" style="width: 250px;" clearable/>
              </el-form-item>
              <el-form-item label="微信号" prop="kfWeixinNumber">
                <el-input v-model="seatForm.kfWeixinNumber" style="width: 250px;" clearable/>
              </el-form-item>
              <el-form-item label="微信二维码" prop="kfWeixiuImg">
                <el-upload
                  ref="uploadImage"
                  :class="{disabled:showImage}"
                  :limit="1"
                  :file-list="dialogImageUrl"
                  :on-preview="handlePictureCardPreview"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :auto-upload="false"
                  action="string"
                  list-type="picture-card"
                >
                  <i class="el-icon-plus"/>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img :src="dialogImageUrl" width="100%" alt>
                </el-dialog>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="hideSeatTableForm">取 消</el-button>
              <el-button type="primary" @click="saveSeatTable">确 定</el-button>
            </div>
          </el-dialog>
          <!--弹出添加框end-->
          <!--弹出配置维护框start-->
          <el-dialog
            :title="dialog1Status"
            :visible.sync="bindServiceDialogVisible"
            width="550px"
            @close="hideSeatConfigForm"
          >
            <el-form
              ref="form1"
              :model="seatConfig"
              :rules="seatConfigFormRules"
              label-width="100px"
            >
              <el-form-item label="客服" prop="ssoUserId">
                <el-select
                  v-model="seatConfig.ssoUserId"
                  filterable
                  placeholder="请选客服(可搜索)"
                  style="width: 250px;"
                >
                  <el-option
                    v-for="(cus,index) in cusList"
                    :label="cus.kfUserName"
                    :value="cus.kfUserId"
                    :key="index"
                  />
                </el-select>
              </el-form-item>
              <!--
              <el-form-item label="合作商类型" prop="partnerSettleModel">
                <el-select
                  placeholder="合作商类型"
                  style="width: 250px;"
                  v-model="seatConfig.partnerSettleModel"
                  @change="listPartnerCompany"
                >
                  <el-option label="对接" value="dockingSettle"></el-option>
                  <el-option label="扳手" value="banshouCompany"></el-option>
                  <el-option label="商家" value="bussCompany"></el-option>
                </el-select>
              </el-form-item>
              -->
              <el-form-item label="合作商" prop="partnerIds">
                <el-select
                  v-model="seatConfig.partnerIds"
                  filterable
                  multiple
                  placeholder="请选择合作商(可搜索)"
                  style="width: 250px;"
                >
                  <el-option
                    v-for="(pc,index) in partnerCompanyList"
                    :label="pc.partnerCompanyName"
                    :value="pc.partnerCompanyId"
                    :key="index"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="hideSeatConfigForm">取 消</el-button>
              <el-button type="primary" @click="saveSeatConfig">确 定</el-button>
            </div>
          </el-dialog>
          <!--弹出添加框end-->
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style>
.row-bg {
  padding: 10px 0;
  background-color: #f3f3f4;
}
.bg-white {
  background: #ffffff;
}

.p-15 {
  padding: 15px;
}
.p-n {
  padding: 0px;
}
.p-t-5 {
  padding-top: 5px;
}
.min-h-800 {
  min-height: 800px;
}
</style>

<script>
// import { parseTime,pickerOptions} from '@/utils'
import {
  listByPage,
  listAllUser,
  saveSeatTable,
  listAllTraceCus,
  listPartnerCompany,
  addTrackCusServiceObject,
  updateTrackCusServiceObject,
  deleteCusSeat
} from '@/api/seatTable'

export default {
  data() {
    return {
      tableData: [],
      total: 0,
      // pickerOptions:{shortcuts:pickerOptions},
      searchQuery: {
        pageSize: 5,
        pageNumber: 1,
        page: 1,
        keyword: '',
        groupTypeId: ''
      },

      userList: [],

      cusList: [],
      partnerCompanyList: [],

      seatForm: {
        seatTableId: null,
        kfUserId: null,
        skillsGroupId: '',
        kfNickname: null,
        kfWeixinNumber: null,
        kfWeixiuImg: null
      },
      seatFormRules: {
        kfUserId: [
          { required: true, message: '请选择客服用户', trigger: 'change' }
        ],
        skillsGroupId: [
          { required: true, message: '请选择技能组', trigger: 'blur' }
        ],
        kfNickname: [
          { required: false, message: '请填入服务星客服昵称', trigger: 'blur' }
        ],
        kfWeixinNumber: [
          {
            required: false,
            message: '请填入服务星客服微信号',
            trigger: 'blur'
          }
        ],
        kfWeixiuImg: [
          {
            required: false,
            message: '请填入服务星客服微信二维码',
            trigger: 'blur'
          }
        ]
      },
      seatConfig: {
        ssoUserId: '',
        partnerIds: ''
      },

      seatConfigFormRules: {
        ssoUserId: [
          { required: true, message: '请选择客服用户', trigger: 'change' }
        ],
        partnerIds: [
          { required: true, message: '请选择服务对象', trigger: 'blur' }
        ]
      },

      showImage: false,
      disabledSkillsGroup: false,
      dialogImageUrl: [],
      dialogVisible: false,
      seatTableDialogVisible: false,
      bindServiceDialogVisible: false,
      dialogStatus: '创建',
      dialog1Status: '创建',
      value5: [],
      partner: [],

      imageFile: {},
      imageFileList: [],

      bindRelationIsUpdate: false
    }
  },
  created() {
    this.getTableData()
  },

  methods: {
    porpAdd1(obj, status) {
      this.bindServiceDialogVisible = true
      this.dialog1Status = status

      this.listAllTraceOrderCus()
      this.listPartnerCompany()

      this.$nextTick(() => {
        this.$refs['form1'].clearValidate()
      })
      this.bindRelationIsUpdate = false
      this.seatConfig.ssoUserId = obj.kfUserId

      if (!(obj.serviceObjectNames === '' || obj.serviceObjectNames === null)) {
        var regPos = /^\d+(\.\d+)?$/
        if (obj.serviceObjectIds) {
          var strArray = obj.serviceObjectIds.split(',')
          var intArray = []
          strArray.forEach(function(data, index, arr) {
            if (regPos.test(data)) {
              intArray.push(+data)
            }
          })
          this.seatConfig.partnerIds = intArray
        }
        this.bindRelationIsUpdate = true
      } else {
        this.seatConfig.partnerIds = []
      }
    },
    showPioneerUrl(seatTableId) {
      var pioneerUrl
      // 判断系统当前访问的环境
      if (window.location.host.indexOf('dev') > 0) {
        pioneerUrl = 'https://m.test.yunyamooc.com/activity/identity'
      } else {
        pioneerUrl = 'https://m.banshouhui.com/activity/identity'
      }
      pioneerUrl = pioneerUrl + '?pioneerId=' + seatTableId
      this.$alert(pioneerUrl, '开拓师傅注册链接', {
        confirmButtonText: '确定'
      })
    },
    handleChange(file, fileList) {
      const isLt2M = file.size / 1024 / 500 < 1
      console.debug(isLt2M)
      if (!isLt2M) {
        this.$refs.uploadImage.clearFiles()
        this.$message.error('上传头像图片大小不能超过 500kb')
        return false
      }
      this.seatForm.kfWeixiuImg = file.raw
      this.imageFile = file
      this.imageFileList = fileList
      console.log(file, fileList)
      if (fileList.length > 0) {
        this.showImage = true
      }
    },
    handleRemove(file, fileList) {
      this.seatForm.kfWeixiuImg = null
      console.log(file, fileList)
      if (fileList.length === 0) {
        this.showImage = false
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = URL.createObjectURL(file.raw)
      this.dialogVisible = true
    },
    getTableData(init) {
      if (init) {
        // 关键之查询 页码初始化
        this.searchQuery.page = 1
        this.searchQuery.pageSize = 5
      }
      this.searchQuery.pageNumber =
        (this.searchQuery.page - 1) * this.searchQuery.pageSize
      listByPage(this.searchQuery).then(response => {
        if (response.data.status === 'success') {
          this.tableData = response.data.data.list
          this.total = response.data.data.total
        }
      })
    },

    handleSizeChange(val) {
      this.searchQuery.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.searchQuery.page = val
      this.getTableData()
    },

    getUserAll() {
      listAllUser().then(response => {
        if (response.data.status === 'success') {
          this.userList = response.data.data
        }
      })
    },

    listAllTraceOrderCus() {
      listAllTraceCus().then(response => {
        if (response.data.status === 'success') {
          this.cusList = response.data.data
        }
      })
    },

    listPartnerCompany(model) {
      var param = { partnerSettleModel: '' }
      listPartnerCompany(param).then(response => {
        if (response.data.status === 'success') {
          this.partnerCompanyList = response.data.data
        }
      })
    },

    showSeatTable(obj, status) {
      this.seatTableDialogVisible = true
      this.dialogStatus = status
      this.getUserAll()
      this.$nextTick(() => {
        this.$refs['seatTableForm'].clearValidate()
      })
      if (obj) {
        this.seatForm.seatTableId = obj.seatTableId
        this.seatForm.kfUserId = obj.kfUserId
        this.seatForm.kfUserName = obj.kfUserName
        this.seatForm.skillsGroupId = obj.skillsGroupId + ''
        this.seatForm.kfNickname = obj.kfNickname
        this.seatForm.kfWeixinNumber = obj.kfWeixinNumber
        this.seatForm.kfWeixiuImg = obj.kfWeixiuImg
        if (!(obj.kfWeixiuImg === null || obj.kfWeixiuImg === '')) {
          this.dialogImageUrl = [{ name: 'photo', url: obj.kfWeixiuImg }]
        }
        this.disabledSkillsGroup = true
        this.showImage = true
      } else {
        this.disabledSkillsGroup = false
      }
    },
    hideSeatTableForm() {
      this.resetForm('seatTableForm')
      this.seatForm.skillsGroupId = ''
      this.seatTableDialogVisible = false
      this.$refs.uploadImage.clearFiles()
    },

    hideSeatConfigForm() {
      this.resetForm('form1')
      this.bindServiceDialogVisible = false
    },

    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    saveSeatTable() {
      this.$refs['seatTableForm'].validate(valid => {
        console.debug(valid)
        if (valid) {
          // 用户名称
          for (var i = this.userList.length - 1; i >= 0; i--) {
            if (this.userList[i].id === this.seatForm.kfUserId) {
              this.seatForm.kfUserName = this.userList[i].name
              break
            }
          }
          var data = new FormData() // 重点在这里 如果使用 var data = {}; data.inputfile=... 这样的方式不能正常上传
          debugger
          data.append(
            'seatTableId',
            this.seatForm.seatTableId == null ? '' : this.seatForm.seatTableId
          )
          data.append(
            'kfUserId',
            this.seatForm.kfUserId == null ? '' : this.seatForm.kfUserId
          )
          data.append(
            'kfUserName',
            this.seatForm.kfUserName == null ? '' : this.seatForm.kfUserName
          )
          data.append(
            'skillsGroupId',
            this.seatForm.skillsGroupId == null
              ? ''
              : this.seatForm.skillsGroupId
          )
          data.append(
            'kfNickname',
            this.seatForm.kfNickname == null ? '' : this.seatForm.kfNickname
          )
          data.append(
            'kfWeixinNumber',
            this.seatForm.kfWeixinNumber == null
              ? ''
              : this.seatForm.kfWeixinNumber
          )
          data.append(
            'kfWeixiuImg',
            this.seatForm.kfWeixiuImg == null ? '' : this.seatForm.kfWeixiuImg
          )
          console.debug(this.seatForm)
          saveSeatTable(data).then(response => {
            if (response.data.status === 'success') {
              this.$message({
                message: '保存成功！',
                type: 'success'
              })
              setTimeout(() => {
                this.hideSeatTableForm()
                this.getTableData()
              }, 1.5 * 1000)
            } else {
              this.$message('保存失败！' + response.data.messge)
            }
          })
        }
      })
    },

    saveSeatConfig() {
      this.seatConfig.serviceObjectIds = this.seatConfig.partnerIds.join(',')

      this.$refs['form1'].validate(valid => {
        if (valid) {
          if (this.bindRelationIsUpdate) {
            updateTrackCusServiceObject(this.seatConfig).then(response => {
              if (response.data.status === 'success') {
                this.$message({
                  message: '修改成功！',
                  type: 'success'
                })
                setTimeout(() => {
                  this.hideSeatConfigForm()
                  this.getTableData()
                }, 1.5 * 1000)
              } else {
                this.$message('修改失败！' + response.data.messge)
              }
            })
          } else {
            addTrackCusServiceObject(this.seatConfig).then(response => {
              if (response.data.status === 'success') {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                })
                setTimeout(() => {
                  this.hideSeatConfigForm()
                  this.getTableData()
                }, 1.5 * 1000)
              } else {
                this.$message('添加失败！' + response.data.messge)
              }
            })
          }
        }
      })
    },

    deleteCusSeat(rowObject) {
      var param = { seatTableId: rowObject.seatTableId }
      this.$confirm('是否删除坐席?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          deleteCusSeat(param).then(response => {
            if (response.data.status === 'success') {
              this.$message({
                message: '删除成功！',
                type: 'success'
              })
              setTimeout(() => {
                this.getTableData()
              }, 1.5 * 1000)
            } else {
              this.$message('删除失败！' + response.data.messge)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    /**
     * 服务星客服添加 启用其他参数校验
     * @return {[type]} [description]
     */
    serivceStarCusAddValidate(changeValue) {
      console.debug(changeValue)
      if (changeValue === '2') {
        this.seatFormRules.kfNickname[0].required = true
        this.seatFormRules.kfWeixinNumber[0].required = true
        this.seatFormRules.kfWeixiuImg[0].required = true
      } else {
        this.seatFormRules.kfNickname[0].required = false
        this.seatFormRules.kfWeixinNumber[0].required = false
        this.seatFormRules.kfWeixiuImg[0].required = false
      }
    }
  }
}
</script>
